package org.mq.mymq.common.remote;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.mq.mymq.common.cache.NameServerSyncFutureManager;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.dto.HeartBeatDTO;
import org.mq.mymq.common.dto.PullBrokerIpRespDTO;
import org.mq.mymq.common.dto.ServiceRegistryRespDTO;
import org.mq.mymq.common.enums.NameServerResponseCode;

/**
 * @ClassName NameServerRemoteRespHandler
 * @Description 处理对nameserver给客户端返回的数据内容
 * @Author jiarong_ye
 * @Date 2025/6/26 12:19
 * @Version 1.0
 */
@ChannelHandler.Sharable
public class NameServerRemoteRespHandler extends SimpleChannelInboundHandler<TcpMsg> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {
        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        if (NameServerResponseCode.REGISTRY_SUCCESS.getCode() == code ||
        NameServerResponseCode.ERROR_USER_OR_PASSWORD.getCode() == code) {
            ServiceRegistryRespDTO serviceRegistryRespDTO = JSON.parseObject(body, ServiceRegistryRespDTO.class);
            SyncFuture syncFuture = NameServerSyncFutureManager.get(serviceRegistryRespDTO.getMsgId());
            if (syncFuture != null) {
                syncFuture.setResponse(tcpMsg);
            }
        } else if (NameServerResponseCode.HEART_BEAT_SUCCESS.getCode() == code) {
            HeartBeatDTO heartBeatDTO = JSON.parseObject(body, HeartBeatDTO.class);
            SyncFuture syncFuture = NameServerSyncFutureManager.get(heartBeatDTO.getMsgId());
            if (syncFuture != null) {
                syncFuture.setResponse(tcpMsg);
            }
        } else if (NameServerResponseCode.PULL_BROKER_ADDRESS_SUCCESS.getCode() == code) {
            PullBrokerIpRespDTO pullBrokerIpRespDTO = JSON.parseObject(body, PullBrokerIpRespDTO.class);
                SyncFuture syncFuture = NameServerSyncFutureManager.get(pullBrokerIpRespDTO.getMsgId());
            if (syncFuture != null) {
                syncFuture.setResponse(tcpMsg);
            }
        }
    }
}
